<template>
  <el-dialog
    v-model="visible"
    title="SQL测试"
    width="1100px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    destroy-on-close
    @close="dialogClosed"
  >
    <div class="flex flex-row p-2" style="height: 600px">
      <div class="w-1/2 pr-2">
        <div class="mb-1">
          <el-link type="primary" @click="showScript(currentItem.sql, '查询SQL')">
            SQL模板：
          </el-link>
        </div>
        <div class="flex flex-row items-center justify-between">
          <div>SQL参数：</div>
          <el-button
            type="primary"
            icon="Position"
            v-hasPermi="['web:db:api:apiDetail:dataApiBoundSql']"
            @click="send"
          >
            发送
          </el-button>
        </div>
        <el-tabs v-model="queryType">
          <el-tab-pane label="Body" name="Body">
            <CodeEditor v-model:value="bodyData" height="474px" />
          </el-tab-pane>
          <el-tab-pane label="Params" name="Params">
            <div class="mb-2">
              <el-button type="primary" @click="addParams"> 添加参数 </el-button>
            </div>
            <el-table :data="paramsData" @selection-change="handleSelectionChange" height="433">
              <el-table-column type="selection" width="40" align="center" />
              <el-table-column label="参数名" prop="label" align="center" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.label" size="small" clearable />
                </template>
              </el-table-column>
              <el-table-column label="参数值" prop="value" align="center" width="130">
                <template #default="{ row }">
                  <el-input v-model="row.value" size="small" clearable />
                </template>
              </el-table-column>
              <el-table-column label="参数描述" prop="remark" align="center">
                <template #default="{ row }">
                  <el-input v-model="row.remark" size="small" clearable />
                </template>
              </el-table-column>
              <el-table-column label="操作" prop="remark" align="center" width="70">
                <template #default="{ $index }">
                  <el-button type="primary" size="small" text @click="deleteParams($index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="w-1/2">
        <div class="font-bold mb-1">SQL模板测试结果：</div>
        <CodeEditor v-model:value="testResult" height="560px" />
      </div>
    </div>

    <script-view v-model="scriptShow" :title="scriptTitle" :content="scriptContent" />
  </el-dialog>
</template>

<script setup>
  import { ref, computed, watch, defineProps, defineEmits } from 'vue';
  import { dataApiBoundSql } from '@/api/web/db/api/api-detail';
  import ScriptView from './script-view';
  import { CodeEditor } from '@/components/CodeEditor';

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => ({}),
    },
  });

  const emits = defineEmits(['update:modelValue']);

  const scriptTitle = ref('');
  const scriptShow = ref(false);
  const scriptContent = ref('');

  const queryType = ref('Body');
  const bodyData = ref('');
  const paramsData = ref([]);
  const testResult = ref('');
  const items = ref([]);

  const visible = computed({
    set(val) {
      emits('update:modelValue', val);
    },
    get() {
      return props.modelValue;
    },
  });

  watch(visible, (v) => {
    if (v) {
      const obj = {};
      const list = [];

      props.currentItem?.apiParams?.forEach((item) => {
        obj[item.name] = item?.example;
        list.push({
          remark: item.remark,
          label: item.name,
          value: null,
        });
      });

      bodyData.value = JSON.stringify(obj);
      paramsData.value = list;
      testResult.value = '';
      items.value = [];
    }
  });

  function addParams() {
    const obj = {
      remark: null,
      label: null,
      value: null,
    };
    paramsData.value.push(obj);
  }

  function deleteParams(index) {
    paramsData.value.splice(index, 1);
  }

  function handleSelectionChange(selection) {
    items.value = selection.map((item) => item);
  }

  function send() {
    const params = {};
    items.value.forEach((item) => {
      params[item.label] = item.value;
    });
    const data = JSON.parse(bodyData.value || '{}');
    const id = props.currentItem.id;
    dataApiBoundSql(
      id,
      params,
      data,
      props.currentItem.encrypt,
      props.currentItem.encryptAlgorithm,
      props.currentItem.encryptKey,
    ).then((res) => {
      testResult.value = res.data;
    });
  }

  function showScript(content, title) {
    scriptContent.value = content;
    scriptTitle.value = title;
    scriptShow.value = true;
  }

  function dialogClosed() {
    scriptTitle.value = '';
    scriptShow.value = false;
    scriptContent.value = '';
    queryType.value = 'Body';
    bodyData.value = '';
    paramsData.value = [];
    testResult.value = '';
    items.value = [];
  }
</script>

<style scoped lang="scss"></style>
